import os
from datetime import timedelta
import uuid

from minio import Minio
from minio.error import S3Error

class MinioDb():
    def __init__(self, endpoint, access_key, secret_key, bucket_name):
        try:
            # 建立数据库连接
            self.client = Minio(
                endpoint=endpoint,
                access_key=access_key,
                secret_key=secret_key,
                secure=False
            )
            self.bucket_name = bucket_name
            self.create_bucket(bucket_name)
        except S3Error as err:
            print(err)
    def create_bucket(self, bucket_name):
        if not self.client.bucket_exists(bucket_name):
            self.client.make_bucket(bucket_name)
            print(f"Bucket {bucket_name} created successfully.")

    def put_obj(self, file):
        # 使用put_object方法上传文件（需要手动打开文件）
        try:
            file.seek(0)
            # 重置文件流指针到开头
            file_size = len(file.read())
            file.seek(0)
            unique_filename = f"{uuid.uuid4().hex}.mp3"
            self.client.put_object(self.bucket_name, unique_filename, file, file_size)
            stored_path = f"{self.bucket_name}/{unique_filename}"
            return stored_path
        except S3Error as err:
            print(err)

    def put_obj_by_path(self, file_path,object_name):
        # 使用put_object方法上传文件（需要手动打开文件）
        try:
            with open(file_path, 'rb') as file_data:
                self.client.put_object(self.bucket_name, object_name, file_data, length=os.path.getsize(file_path))
                print(f"File {object_name} uploaded successfully.")
        except S3Error as err:
            print(err)

    def fput_obj_by_path(self, file_path,object_name):
        # 或者使用fput_object方法上传文件（直接指定文件路径）
        try:
            self.client.fput_object(self.bucket_name, object_name, file_path, content_type='text/plain')
            print(f"File {object_name} uploaded with fput_object.")
        except S3Error as err:
            print(err)

    def download_file(self, bucket_name,object_name,path):
        # 下载文件并保存到本地
        try:
            data = self.client.get_object(bucket_name, object_name)
            with open(path, "wb") as fp:
                for d in data.stream(1024):
                    fp.write(d)
            print(f"File {object_name} downloaded successfully.")
        except S3Error as err:
            print(err)

    def del_file(self, bucket_name,object_name):
        try:
            self.client.remove_object(bucket_name, object_name)
            print(f"File {object_name} deleted successfully.")
        except S3Error as err:
            print(err)

    def get_file_url(self, bucket_name,destination_file):
        expires = timedelta(days=1)
        try:
            presigned_url = self.client.presigned_get_object(bucket_name, destination_file, expires=expires)
            print(f"Presigned URL for {destination_file}: {presigned_url}")
        except Exception as err:
            print(f"Failed to generate presigned URL: {err}")
